import { Table, Space, Button, Card, message, Cascader, Image, Breadcrumb, Form, Select, InputNumber, Modal ,Input} from "antd";
import { useEffect, useState } from "react";
import { useHistory } from "react-router";
import { useComms } from "../../hook/comms";
import { useShopping } from "../../hook/shopping";
import { useAllTypes } from "../../hook/allTypes"

import _ from "lodash";


const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};


//eslint-disable-next-line
export default () => {
  const history = useHistory()
  const [allType, { getAllTypes }] = useAllTypes();
  const [,{addCart}]=useShopping()
  const [{ rows, eachPage, curPage, total }, { getComms, setCurPage, delComm }] = useComms();
  const [childId, setChildId] = useState("")
  const [commId, setcommId] = useState("")
  const { form } = Form
  // 数据请求
  useEffect(() => {
    async function fetchData() {
      await getAllTypes()
    }
    fetchData();
    getComms(childId);
  }, [getComms, childId, getAllTypes]);

  const [isModalVisible, setIsModalVisible] = useState(false);

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 选择规格
  const reset = async _id => {
    setcommId(_id)
    setIsModalVisible(true)
  }



  const options = _.map(allType, item => {
    return {
      label: item.title,
      value: item._id,
      children: _.map(item.labels, i => {
        return {
          label: i.title,
          value: i._id
        }
      })
    }
  })

  const onFinish =async (values) => {
    const { num,userid } = values
    const data = await addCart({num,userid,shoppingid:commId })
    if (data) {
      message.success('添加成功！');
      getComms(childId);
    } else {
        message.error('添加失败！');
    }
  };


  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '库存',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '商品详情',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '商品海报',
      dataIndex: 'poster',
      key: 'poster',
      render: record => {
        return record[0] ? <Image width={50} src={`http://localhost:3002${record[0]}`} /> : <p>暂无图片</p>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: record => (
        <Space size="middle">
          <Button type="primary" size="small" onClick={() => reset(record._id)}>加入购物车</Button>
          <Modal footer={null} title="Basic Modal" visible={isModalVisible}>
            <Form
              {...formItemLayout}
              form={form}
              name="addComm"
              onFinish={onFinish}
              scrollToFirstError
              style={{ width: "500px", margin: "auto" }}
            >
              <Form.Item
                name="num"
                label="数量"
                rules={[
                  {
                    required: true,
                    message: '请输入数量！',
                  },
                ]}
              >
                <InputNumber min={0} max={5} />
              </Form.Item>

              <Form.Item
                name="userid"
                label="用户"
                rules={[
                  {
                    required: true,
                    message: '请选择用户！',
                  },
                ]}
                initialValue="61a056228729d31230764bc8"
              >
                <Input style={{width:"200px"}}  />
              </Form.Item>
              <Form.Item {...tailFormItemLayout} style={{ display: "flex", alignItems: "center" }}>
                <div style={{ width: "200px", display: "flex", justifyContent: "space-between" }}>
                  <Button type="primary" htmlType="submit">
                    新增秒杀商品
                  </Button>
                  <Button onClick={() => handleCancel()}>
                    取消
                  </Button>
                </div>
              </Form.Item>
            </Form>
          </Modal>
        </Space>
      ),
    },
  ];

  // 下拉框选择完成之后
  const onChange = (value) => {
    console.log(value);
    setChildId(value[1])
  }

  return (
    <div className="site-card-border-less-wrapper">

      <Card title="查询" bordered={true}>
        <Cascader options={options} placeholder="请选择商品类型" onChange={onChange}></Cascader>
      </Card>
      <div style={{ height: "30px" }}></div>

      <Card title="商品列表" bordered={true}>
        <Card>
          <Breadcrumb>
            <Breadcrumb.Item>主页</Breadcrumb.Item>
            <Breadcrumb.Item>
              商品
            </Breadcrumb.Item>
          </Breadcrumb>
        </Card>
        <Table style={{ maeginTop: "20px" }} columns={columns} pagination={{
          current: curPage, pageSize: eachPage, total, onChange: setCurPage
        }} dataSource={rows} rowKey={record => record._id} />
      </Card>
    </div>
  )
}